package com.lagou.sqlSession;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;

import java.lang.reflect.*;
import java.util.List;

/**
 * @author stevejson
 */
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    private Executor executor = new SimpleExecutor();

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        return executor.query(configuration, configuration.getMappedStatementMap().get(statementId), params);
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<T> objects = this.selectList(statementId, params);
        if (objects.size() == 1) {
            return objects.get(0);
        } else {
            System.out.println(objects);
            throw new RuntimeException("查询结果不为1");
        }
    }

    @Override
    public int insert(String statementId, Object... params) throws Exception {
        return update(statementId, params);
    }

    @Override
    public int update(String statementId, Object... params) throws Exception {
        return executor.update(configuration, configuration.getMappedStatementMap().get(statementId), params);

    }

    @Override
    public int delete(String statementId, Object... params) throws Exception {
        return update(statementId, params);
    }


    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        //使用jdk动态代理 来为dao生成实现类并返回
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[] {mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //可以通过调用selectAll和selectOne来进行查询

                //statementId拿不到，所以限定死namespace.id   namespace是接口全限定名，id是接口方法名
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String statementId = className + "." + methodName;
                MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
                //根据返回值类型判断selectList 还是selectOne
                Type genericReturnType = method.getGenericReturnType();
                switch (mappedStatement.getSqlCommandType()) {
                    case SELECT: {
                        //是否有泛型，有认为是个集合（简单处理）
                        if (genericReturnType instanceof ParameterizedType) {
                            return selectList(statementId);
                        }
                        return selectOne(statementId, args);
                    }
                    case INSERT: {
                        return insert(statementId, args);

                    }
                    case DELETE: {
                        return delete(statementId, args);
                    }

                    case UPDATE:{
                        return update(statementId, args);
                    }
                    default: {
                        throw new RuntimeException("Unknown sqlCommandType for: " + mappedStatement.getSqlCommandType());
                    }
                }
            }
        });


        return (T) proxyInstance;
    }


}
